﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace I_Ear_Tag.Infrastructure
{
    public class BaseRepostitory<T> : IRepository<T> where T : class, new()
    {
        private readonly EFDbContext context;
        public BaseRepostitory(EFDbContext context)
        {
            this.context = context;
        }

        public async Task<int> AddAsync(T t)
        {
            await context.Set<T>().AddAsync(t);
            return await context.SaveChangesAsync();
        }

        public async Task<int> AddAsync(List<T> t)
        {
            await context.Set<T>().AddRangeAsync(t);
            return await context.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            var smilt = await context.Set<T>().FindAsync(id);
            context.Set<T>().Remove(smilt);
            return await context.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(Expression<Func<T, bool>> expression)
        {
            var query = await context.Set<T>().Where(expression).ToListAsync();
            context.Set<T>().RemoveRange(query);
            return await context.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await context.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await context.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await context.Set<T>().FindAsync(id);
        }

        public async Task<T> GetModelAsync(Expression<Func<T, bool>> expression)
        {
            return await context.Set<T>().FirstOrDefaultAsync(expression);
        }

        public async Task<int> StateDelete(T t)
        {
            context.Set<T>().Update(t);
            return await context.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(T t)
        {
            context.Update(t);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(List<T> t)
        {
            context.UpdateRange(t);
            return await context.SaveChangesAsync();
        }
    }
}
